﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Collections.Specialized;


namespace Nivdal
{
    public partial class PayPal_IPN : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            using (StreamWriter w = File.AppendText("c:\\Nivdal\\log.txt"))
            {
                Log("entered PaypalIPN Code behind", w);
                // Close the writer and underlying file.
                w.Close();
            }
            
            
            //Post back to either sandbox or live
            string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
            string strLive = "https://www.paypal.com/cgi-bin/webscr";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            byte[] param = Request.BinaryRead(HttpContext.Current.Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            string strResponse_copy = strRequest;  //Save a copy of the initial info sent by PayPal
            strRequest += "&cmd=_notify-validate";
            req.ContentLength = strRequest.Length;

            StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
            streamOut.Write(strRequest);
            streamOut.Close();
            StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
            string strResponse = streamIn.ReadToEnd();
            streamIn.Close();
            NameValueCollection these_argies = HttpUtility.ParseQueryString(strResponse_copy);
            string user_email = these_argies["payer_email"];
            string pay_stat = these_argies["payment_status"];
            string txn_id = these_argies["txn_id"];
            string payment_gross = these_argies["payment_gross"];
            string custom = these_argies["custom"]; //sponserid

                        if (strResponse == "VERIFIED")
            {

                if (pay_stat.Equals("Completed"))
                {

                    GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
                    string[] Users = custom.Split(',');

                    if (Users.Length < 3)
                    {
                        using (StreamWriter w = File.AppendText("log.txt"))
                        {


                            //log for manual investigation
                            Log("problem reading payment details. custom is: " + custom, w);
                            GND.ExecNivdalSQL("Note", "Nivdal_LogPaymentProblem", custom);


                            // Close the writer and underlying file.
                            w.Close();
                        }
                    }
                    else
                    {
                        string PaymentType = Users[0];
                        String UserId = Users[1];
                        String OnlineUserId = Users[2];

                        using (StreamWriter w = File.AppendText("log.txt"))
                        {


                            //log for manual investigation
                            Log("VALID: log for manual investigation: " + " pay_stat is: " + pay_stat + " user_email: " + user_email + " payment_gross is: " + payment_gross + " txn_id is: "
                                + txn_id + " OnlineUserId is: " + OnlineUserId + " UserId is: " + UserId + " paymentType: " + PaymentType, w);
                            // Close the writer and underlying file.
                            w.Close();
                        }
                        if (PaymentType == "0" || PaymentType == "1")
                            GND.ExecNivdalSQL("UserId", "OnlineUserId ", "Ammount", "Nivdal_ProlonguePremiumForUser", UserId, OnlineUserId, payment_gross);
                        else if (PaymentType == "2")
                        {
                            // pay attention to SetTournamentButtonClick in Shop.aspx. Here UserId actually means TournamentId
                            GND.ExecNivdalSQL("UserId", "TournamentId", "Ammount", "Nivdal_PayForTournamentPrice", OnlineUserId, UserId, payment_gross);
                        }

                        //GND.ExecNivdalSQL("UserId", "Ammount", "Nivdal_ProlonguePremiumForUser", custom, payment_gross);

                    }
                   
                }


                // more checks needed here specially your account number and related stuff
            }
            else if (strResponse == "INVALID")
            {
                using (StreamWriter w = File.AppendText("log.txt"))
                {
                    //log for manual investigation
                    Log("INVALID: log for manual investigation: " + " pay_stat is: " + pay_stat + " payment_gross is: " + payment_gross + " txn_id is: " + txn_id + " custom is: " + custom, w);
                    // Close the writer and underlying file.
                    w.Close();
                }

            }
            else
            {
                //log response/ipn data for manual investigation
                using (StreamWriter w = File.AppendText("log.txt"))
                {
                    Log("Else response/ipn log for manual investigation: " + " pay_stat is: " + pay_stat + " payment_gross is: " + payment_gross + " txn_id is: " + txn_id + " custom is: " + custom, w);
                    //// Close the writer and underlying file.
                    w.Close();
                }

            }

        }

        public static void Log(string logMessage, TextWriter w)
        {
            w.Write("\r\nLog Entry : ");
            w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            w.WriteLine("  :");
            w.WriteLine("  :{0}", logMessage);
            w.WriteLine("-------------------------------");
            // Update the underlying file.
            w.Flush();
        }

        public static void DumpLog(StreamReader r)
        {
            // While not at the end of the file, read and write lines.
            string line;
            while ((line = r.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
            r.Close();
        }

        //protected void SendEmail(string from, string to, string subject, string body)
        //{

        //    //create the mail message
        //    MailMessage mail = new MailMessage();
        //    mail.IsBodyHtml = true;
        //    //set the addresses
        //    mail.From = new MailAddress(from);
        //    mail.To.Add(to);
        //    //set the content
        //    mail.Subject = subject;
        //    mail.Body = body;
        //    SmtpClient smtp = new SmtpClient("127.0.0.1");
        //    try
        //    {
        //        smtp.Send(mail);
        //    }
        //    catch (Exception exc)
        //    {
        //        MessageLabel.Text = ("Send failure: " + exc.ToString());
        //    }

        //} 

    }       

}